<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-wrapper">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入部门名称" clearable />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card shadow="never" class="table-wrapper">
      <template #header>
        <div class="card-header">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>新增
          </el-button>
          <el-button type="success" @click="handleExpandAll">
            <el-icon><Expand /></el-icon>展开/折叠
          </el-button>
        </div>
      </template>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="deptList"
        row-key="id"
        border
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="name" label="部门名称" min-width="180" />
        <el-table-column prop="sort" label="排序" width="80" align="center" />
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status ? 'success' : 'danger'">
              {{ row.status ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleAdd(row)">
              <el-icon><Plus /></el-icon>新增
            </el-button>
            <el-button type="primary" link @click="handleUpdate(row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑部门对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      append-to-body
      destroy-on-close
    >
      <el-form
        ref="deptFormRef"
        :model="deptForm"
        :rules="deptRules"
        label-width="80px"
      >
        <el-form-item label="上级部门" prop="parent_id">
          <el-tree-select
            v-model="deptForm.parent_id"
            :data="deptOptions"
            placeholder="请选择上级部门"
            :props="{ label: 'name', value: 'id', children: 'children' }"
            check-strictly
            clearable
          />
        </el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="deptForm.name" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="deptForm.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="deptForm.status">
            <el-radio :label="true">启用</el-radio>
            <el-radio :label="false">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, Expand } from '@element-plus/icons-vue'
import { useThemeStore } from '@/store/theme'
import { getDepartments, getDepartmentTree, getDepartment, createDepartment, updateDepartment, deleteDepartment } from '@/api/department'

// 查询参数
const queryParams = reactive({
  name: '',
  status: null
})

// 表格数据
const deptList = ref([])
const loading = ref(false)
const isExpandAll = ref(true)

// 部门树形选项
const deptOptions = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add') // add 或 update
const dialogTitle = ref('添加部门')
const deptFormRef = ref(null)
const queryFormRef = ref(null)

// 部门表单
const deptForm = reactive({
  id: null,
  parent_id: null,
  name: '',
  sort: 0,
  status: true
})

// 表单校验规则
const deptRules = {
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ]
}

// 获取部门列表
const getDeptList = async () => {
  loading.value = true
  try {
    const res = await getDepartmentTree(queryParams)
    deptList.value = res.data
  } catch (error) {
    console.error('获取部门列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取部门树形数据（用于选择上级部门）
const getDeptTreeData = async () => {
  try {
    const res = await getDepartmentTree()
    deptOptions.value = [{ id: 0, name: '顶级部门', children: res.data }]
  } catch (error) {
    console.error('获取部门树形数据失败:', error)
  }
}

// 查询
const handleQuery = () => {
  getDeptList()
}

// 重置查询
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

// 展开/折叠
const handleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value
  deptList.value = [...deptList.value]
}

// 添加部门
const handleAdd = (row) => {
  resetDeptForm()
  dialogType.value = 'add'
  dialogTitle.value = '添加部门'
  
  if (row && row.id) {
    // 如果是添加子部门，设置父部门ID
    deptForm.parent_id = row.id
  }
  
  dialogVisible.value = true
}

// 编辑部门
const handleUpdate = async (row) => {
  resetDeptForm()
  dialogType.value = 'update'
  dialogTitle.value = '编辑部门'
  
  try {
    const res = await getDepartment(row.id)
    const deptData = res.data
    
    // 填充表单数据
    deptForm.id = deptData.id
    deptForm.parent_id = deptData.parent_id
    deptForm.name = deptData.name
    deptForm.sort = deptData.sort
    deptForm.status = deptData.status
    
    dialogVisible.value = true
  } catch (error) {
    console.error('获取部门详情失败:', error)
    ElMessage.error('获取部门详情失败')
  }
}

// 删除部门
const handleDelete = (row) => {
  // 检查是否有子部门
  if (row.children && row.children.length > 0) {
    ElMessage.warning('该部门下存在子部门，无法删除')
    return
  }
  
  ElMessageBox.confirm(`确认删除部门 ${row.name} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteDepartment(row.id)
      ElMessage.success('删除成功')
      getDeptList()
    } catch (error) {
      console.error('删除部门失败:', error)
      ElMessage.error('删除部门失败')
    }
  }).catch(() => {})
}

// 重置部门表单
const resetDeptForm = () => {
  deptForm.id = null
  deptForm.parent_id = null
  deptForm.name = ''
  deptForm.sort = 0
  deptForm.status = true
  
  if (deptFormRef.value) {
    deptFormRef.value.resetFields()
  }
}

// 提交表单
const submitForm = () => {
  deptFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          // 创建部门
          await createDepartment(deptForm)
          ElMessage.success('添加成功')
        } else {
          // 更新部门
          await updateDepartment(deptForm.id, deptForm)
          ElMessage.success('更新成功')
        }
        
        dialogVisible.value = false
        getDeptList()
        getDeptTreeData() // 更新部门树形数据
      } catch (error) {
        console.error('保存部门失败:', error)
        ElMessage.error('保存部门失败')
      }
    }
  })
}

onMounted(() => {
  getDeptList()
  getDeptTreeData()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 0;
  
  .search-wrapper {
    margin-bottom: 20px;
    border: 1px solid var(--border-color);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
    
    :deep(.el-card__body) {
      background-color: var(--card-bg-color);
      padding: 20px;
    }
    
    :deep(.el-form) {
      .el-form-item {
        margin-bottom: 16px;
        
        .el-form-item__label {
          color: var(--text-color);
          font-weight: 500;
        }
        
        .el-input__wrapper {
          border-radius: 6px;
          transition: all 0.3s ease;
          background-color: var(--card-bg-color);
          
          &:hover {
            border-color: var(--border-color);
          }
          
          &.is-focus {
            border-color: #409eff;
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
          }
        }
        
        .el-select {
          .el-input__wrapper {
            border-radius: 6px;
            background-color: var(--card-bg-color);
          }
        }
        
        .el-button {
          border-radius: 6px;
          font-weight: 500;
          transition: all 0.3s ease;
          
          &:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
          }
        }
      }
    }
  }
  
  .table-wrapper {
    border: 1px solid var(--border-color);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
    
    :deep(.el-card__header) {
      background-color: var(--header-bg-color);
      border-bottom: 1px solid var(--border-color);
      
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .el-button {
          border-radius: 6px;
          font-weight: 500;
          transition: all 0.3s ease;
          
          &:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
          }
        }
      }
    }
    
    :deep(.el-card__body) {
      background-color: var(--card-bg-color);
      padding: 20px;
    }
    
    :deep(.el-table) {
      border-radius: 6px;
      overflow: hidden;
      background-color: var(--card-bg-color);
      
      .el-table__header {
        th {
          background-color: var(--header-bg-color);
          color: var(--text-color);
          font-weight: 600;
          border-bottom: 1px solid var(--border-color);
        }
      }
      
      .el-table__body {
        tr {
          background-color: var(--card-bg-color);
          
          &:hover > td {
            background-color: var(--hover-bg-color) !important;
          }
          
          td {
            border-bottom: 1px solid var(--border-color);
            color: var(--text-color);
            
            .el-tag {
              border-radius: 4px;
              font-weight: 500;
            }
            
            .el-button {
              border-radius: 4px;
              font-weight: 500;
              transition: all 0.3s ease;
              color: var(--text-color);
              
              &:hover {
                transform: translateY(-1px);
              }
            }
          }
        }
      }
      
      // 树形表格特殊样式
      .el-table__expand-icon {
        color: #409eff;
        transition: all 0.3s ease;
        
        &:hover {
          color: #66b1ff;
        }
      }
      
      .el-table__indent {
        border-left: 1px dashed var(--border-color);
      }
    }
  }
}

// 对话框样式优化
:deep(.el-dialog) {
  border-radius: 8px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  background-color: var(--card-bg-color);
  
  .el-dialog__header {
    background-color: var(--header-bg-color);
    border-bottom: 1px solid var(--border-color);
    border-radius: 8px 8px 0 0;
    
    .el-dialog__title {
      color: var(--text-color);
      font-weight: 600;
    }
  }
  
  .el-dialog__body {
    background-color: var(--card-bg-color);
    padding: 24px;
    color: var(--text-color);
    
    .el-form {
      .el-form-item {
        margin-bottom: 20px;
        
        .el-form-item__label {
          color: var(--text-color);
          font-weight: 500;
        }
        
        .el-input__wrapper,
        .el-tree-select .el-input__wrapper {
          border-radius: 6px;
          transition: all 0.3s ease;
          background-color: var(--card-bg-color);
          
          &:hover {
            border-color: var(--border-color);
          }
          
          &.is-focus {
            border-color: #409eff;
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
          }
        }
        
        .el-input-number {
          .el-input__wrapper {
            border-radius: 6px;
            background-color: var(--card-bg-color);
          }
        }
        
        .el-radio-group {
          .el-radio {
            margin-right: 20px;
            
            .el-radio__label {
              color: var(--text-color);
            }
          }
        }
      }
    }
  }
  
  .el-dialog__footer {
    background-color: var(--header-bg-color);
    border-top: 1px solid var(--border-color);
    border-radius: 0 0 8px 8px;
    
    .dialog-footer {
      .el-button {
        border-radius: 6px;
        font-weight: 500;
        transition: all 0.3s ease;
        
        &:hover {
          transform: translateY(-1px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
      }
    }
  }
}

// 树形选择器下拉面板样式
:deep(.el-tree-select__popper) {
  .el-tree {
    background-color: var(--card-bg-color);
    
    .el-tree-node {
      .el-tree-node__content {
        border-radius: 4px;
        transition: all 0.3s ease;
        
        &:hover {
          background-color: var(--hover-bg-color);
        }
      }
      
      .el-tree-node__label {
        color: var(--text-color);
        font-weight: 500;
      }
    }
  }
}
</style>
